package com.luo.backend.service;

import com.luo.backend.dto.*;
import com.luo.backend.entity.*;
import com.luo.backend.repository.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统服务类
 */
@Service
public class SystemService {
    
    private static final Logger logger = LoggerFactory.getLogger(SystemService.class);
    
    // 文件上传配置
    private static final String UPLOAD_DIR = "uploads";
    private static final String[] ALLOWED_IMAGE_TYPES = {"image/jpeg", "image/png", "image/gif", "image/webp"};
    private static final String[] ALLOWED_DOCUMENT_TYPES = {"application/pdf", "text/plain", "application/msword"};
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
    
    @Autowired
    private FoodRepository foodRepository;
    
    @Autowired
    private MerchantRepository merchantRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private GroupBuyingActivityRepository groupBuyingActivityRepository;
    
    /**
     * 获取首页数据
     */
    public HomeResponse getHomeData() {
        logger.info("获取首页数据");
        
        HomeResponse response = new HomeResponse();
        
        // 轮播图数据（模拟）
        List<HomeResponse.BannerInfo> banners = Arrays.asList(
            new HomeResponse.BannerInfo(1L, "新用户专享优惠", "/static/banner1.jpg", "/merchants", "merchant"),
            new HomeResponse.BannerInfo(2L, "爆款团购活动", "/static/banner2.jpg", "/group-buying", "group_buying"),
            new HomeResponse.BannerInfo(3L, "免配送费活动", "/static/banner3.jpg", "/foods", "food")
        );
        response.setBanners(banners);
        
        // 热门商品
        Pageable hotFoodsPageable = PageRequest.of(0, 6);
        List<Food> hotFoodsList = foodRepository.findByIsHotAndStatus(1, 1, hotFoodsPageable).getContent();
        List<FoodResponse> hotFoods = hotFoodsList.stream()
            .map(food -> {
                FoodResponse foodResponse = new FoodResponse(food);
                // 设置商家信息
                Optional<Merchant> merchantOpt = merchantRepository.findById(food.getMerchantId());
                if (merchantOpt.isPresent()) {
                    Merchant merchant = merchantOpt.get();
                    FoodResponse.MerchantInfo merchantInfo = new FoodResponse.MerchantInfo(
                        merchant.getId(),
                        merchant.getName(),
                        merchant.getMinOrderAmount(),
                        merchant.getDeliveryFee()
                    );
                    merchantInfo.setLogo(merchant.getLogo()); // ⭐ 设置商家Logo
                    foodResponse.setMerchant(merchantInfo);
                }
                return foodResponse;
            })
            .collect(Collectors.toList());
        response.setHotFoods(hotFoods);
        
        // 推荐商品
        Pageable recommendedFoodsPageable = PageRequest.of(0, 8);
        List<Food> recommendedFoodsList = foodRepository.findByIsRecommendedAndStatus(1, 1, recommendedFoodsPageable).getContent();
        List<FoodResponse> recommendedFoods = recommendedFoodsList.stream()
            .map(food -> {
                FoodResponse foodResponse = new FoodResponse(food);
                // 设置商家信息
                Optional<Merchant> merchantOpt = merchantRepository.findById(food.getMerchantId());
                if (merchantOpt.isPresent()) {
                    Merchant merchant = merchantOpt.get();
                    FoodResponse.MerchantInfo merchantInfo = new FoodResponse.MerchantInfo(
                        merchant.getId(),
                        merchant.getName(),
                        merchant.getMinOrderAmount(),
                        merchant.getDeliveryFee()
                    );
                    merchantInfo.setLogo(merchant.getLogo()); // ⭐ 设置商家Logo
                    foodResponse.setMerchant(merchantInfo);
                }
                return foodResponse;
            })
            .collect(Collectors.toList());
        response.setRecommendedFoods(recommendedFoods);
        
        // 活跃团购（这里需要注入GroupBuyingService，但为了简单直接查询）
        Pageable activeGroupBuyingPageable = PageRequest.of(0, 4);
        List<GroupBuyingActivity> activeGroupBuyingList = groupBuyingActivityRepository.findActiveActivities(activeGroupBuyingPageable).getContent();
        List<GroupBuyingResponse> activeGroupBuying = activeGroupBuyingList.stream()
            .map(activity -> {
                GroupBuyingResponse groupResponse = new GroupBuyingResponse(activity);
                // 设置基本信息（简化版）
                Optional<Food> foodOpt = foodRepository.findById(activity.getFoodId());
                if (foodOpt.isPresent()) {
                    Food food = foodOpt.get();
                    groupResponse.setFoodName(food.getName());
                    groupResponse.setFoodImage(food.getImage());
                }
                Optional<Merchant> merchantOpt = merchantRepository.findById(activity.getMerchantId());
                if (merchantOpt.isPresent()) {
                    groupResponse.setMerchantName(merchantOpt.get().getName());
                }
                return groupResponse;
            })
            .collect(Collectors.toList());
        response.setActiveGroupBuying(activeGroupBuying);
        
        // 热门商家
        Pageable popularMerchantsPageable = PageRequest.of(0, 5);
        List<Merchant> popularMerchantsList = merchantRepository.findByStatusOrderByRatingDescSoldCountDesc(1, popularMerchantsPageable).getContent();
        List<MerchantResponse> popularMerchants = popularMerchantsList.stream()
            .map(MerchantResponse::new)
            .collect(Collectors.toList());
        response.setPopularMerchants(popularMerchants);
        
        // 系统统计
        Long totalUsers = userRepository.count();
        Long totalMerchants = merchantRepository.count();
        Long totalFoods = foodRepository.count();
        Long totalOrders = orderRepository.count();
        Long activeGroupBuyingCount = (long) activeGroupBuyingList.size();
        
        HomeResponse.SystemStats stats = new HomeResponse.SystemStats(
            totalUsers, totalMerchants, totalFoods, totalOrders, activeGroupBuyingCount
        );
        response.setStats(stats);
        
        return response;
    }
    
    /**
     * 获取系统配置
     */
    public SystemConfigResponse getSystemConfig() {
        logger.info("获取系统配置");
        
        SystemConfigResponse response = new SystemConfigResponse();
        
        // 应用配置
        SystemConfigResponse.AppConfig appConfig = new SystemConfigResponse.AppConfig(
            "美食外卖拼单平台",
            "1.0.0",
            "/static/logo.png",
            "专业的美食外卖拼单平台，享受更优惠的价格",
            "400-123-4567",
            "service@foodplatform.com",
            "https://example.com/privacy",
            "https://example.com/agreement"
        );
        response.setApp(appConfig);
        
        // 配送配置
        String[] timeSlots = {"09:00-11:00", "11:00-13:00", "13:00-15:00", "15:00-17:00", "17:00-19:00", "19:00-21:00"};
        SystemConfigResponse.DeliveryConfig deliveryConfig = new SystemConfigResponse.DeliveryConfig(
            3.0, 30.0, 45, timeSlots
        );
        response.setDelivery(deliveryConfig);
        
        // 支付配置
        String[] paymentMethods = {"wechat", "alipay", "cash"};
        SystemConfigResponse.PaymentConfig paymentConfig = new SystemConfigResponse.PaymentConfig(
            paymentMethods, true, true, false
        );
        response.setPayment(paymentConfig);
        
        // 团购配置
        SystemConfigResponse.GroupBuyingConfig groupBuyingConfig = new SystemConfigResponse.GroupBuyingConfig(
            100, 72, 0.8, true
        );
        response.setGroupBuying(groupBuyingConfig);
        
        // 其他配置
        Map<String, Object> others = new HashMap<>();
        others.put("maintenance_mode", false);
        others.put("registration_enabled", true);
        others.put("guest_checkout", false);
        others.put("rating_required", true);
        response.setOthers(others);
        
        return response;
    }
    
    /**
     * 文件上传
     */
    public UploadResponse uploadFile(MultipartFile file) throws IOException {
        logger.info("上传文件: {}", file.getOriginalFilename());
        
        // 验证文件
        validateFile(file);
        
        // 创建上传目录
        String uploadPath = createUploadPath();
        
        // 生成文件名
        String filename = generateFilename(file.getOriginalFilename());
        String filePath = uploadPath + File.separator + filename;
        
        // 保存文件
        Path path = Paths.get(filePath);
        Files.copy(file.getInputStream(), path);
        
        // 计算文件哈希
        String hash = calculateFileHash(file.getBytes());
        
        // 生成访问URL
        String url = "/uploads/" + getDatePath() + "/" + filename;
        String fullUrl = "http://localhost:8080" + url;
        
        UploadResponse response = new UploadResponse(
            filename,
            file.getOriginalFilename(),
            url,
            fullUrl,
            file.getSize(),
            file.getContentType(),
            hash
        );
        
        logger.info("文件上传成功: {}", filename);
        return response;
    }
    
    /**
     * 验证文件
     */
    private void validateFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }
        
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new RuntimeException("文件大小不能超过10MB");
        }
        
        String contentType = file.getContentType();
        boolean isValidType = Arrays.asList(ALLOWED_IMAGE_TYPES).contains(contentType) ||
                             Arrays.asList(ALLOWED_DOCUMENT_TYPES).contains(contentType);
        
        if (!isValidType) {
            throw new RuntimeException("不支持的文件类型: " + contentType);
        }
    }
    
    /**
     * 创建上传路径
     */
    private String createUploadPath() throws IOException {
        String datePath = getDatePath();
        String uploadPath = UPLOAD_DIR + File.separator + datePath;
        
        File directory = new File(uploadPath);
        if (!directory.exists()) {
            boolean created = directory.mkdirs();
            if (!created) {
                throw new IOException("无法创建上传目录: " + uploadPath);
            }
        }
        
        return uploadPath;
    }
    
    /**
     * 获取日期路径
     */
    private String getDatePath() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
    }
    
    /**
     * 生成文件名
     */
    private String generateFilename(String originalFilename) {
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        String random = String.valueOf((int)(Math.random() * 1000));
        
        return timestamp + random + extension;
    }
    
    /**
     * 计算文件哈希
     */
    private String calculateFileHash(byte[] fileBytes) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hashBytes = md.digest(fileBytes);
            StringBuilder sb = new StringBuilder();
            for (byte b : hashBytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            logger.error("计算文件哈希失败", e);
            return null;
        }
    }
}
